<template>
    <view class="home-page">
        <view class="home-bar-height" :style="{'--bar-height': `${barHeight}px`}" />
        <view class="home-title-container">
            <view>
                <view class="home-main-title">Take Care</view>
            </view>
        </view>
        <view class="home-calendar-container">
            <uni-calendar insert="false" :selected="userData.menstrualDayDetailVOList" @change="selectDayChange"
                @monthSwitch='monthSwitch' :date="today" class="calendar-component" />
            <view class="home-legend-container">
                <view class="home-item-block-sty legend-menstrual" />
                <view class="home-item-block-text">经期</view>
                <view class="home-item-block-sty legend-predicted" />
                <view class="home-item-block-text">预测经期</view>
                <view class="home-item-block-sty legend-ovulation" />
                <view class="home-item-block-text">排卵日</view>
                <view class="home-item-block-sty legend-ovulation-period" />
                <view class="home-item-block-text">排卵期</view>
            </view>
        </view>
        <view class="home-status-panel">
            <view class="home-panel-text">
                {{ today.split('-')[1] + '月' + today.split('-')[2] + '日' }}状态
            </view>
            <uni-forms label-position="left">
                <view v-if="isFutureFlag" class="home-future-text">当前选择了未来日期，不可以进行记录哦~</view>
                <view v-else>
                    <uni-forms-item label="大姨妈来了吗">
                        <template slot="label">
                            <view class="home-bottom-option">
                                <u-icon name="https://miu-bloom.oss-cn-qingdao.aliyuncs.com/icon/from-icon-1.webp"
                                    size="30" />
                                <view class="home-label">
                                    经期来喽
                                </view>
                            </view>
                        </template>
                        <view class="home-segmenter">
                            <view class="segmenter-container">
                                <u-subsection :list="['是', '否']" @change="modelChange" :current="currentStatus"
                                    inactiveColor="#FF80AB" activeColor="#FFFDFE" bgColor="#FFFDFE" />
                            </view>
                        </view>
                    </uni-forms-item>
                    <view v-if="currentStatus == 0">
                        <uni-forms-item label="流量">
                            <template slot="label">
                                <view class="home-bottom-option">
                                    <u-icon name="https://miu-bloom.oss-cn-qingdao.aliyuncs.com/icon/from-icon-2.webp"
                                        size="30" />
                                    <view class="home-label">
                                        流量
                                    </view>
                                </view>
                            </template>
                            <view class="home-right-style" @click="iconClick('flow')">
                                <u-icon v-if="userData.flowShowText == null || userData.flowShowText == ''"
                                    name="plus-circle" color="#FF5184" size="26" />
                                <view class="status-text" v-else>
                                    {{
                    userData.flowShowText
                  }}
                                </view>
                            </view>
                        </uni-forms-item>
                        <uni-forms-item label="颜色">
                            <template slot="label">
                                <view class="home-bottom-option">
                                    <u-icon name="https://miu-bloom.oss-cn-qingdao.aliyuncs.com/icon/from-icon-3.webp"
                                        size="30" />
                                    <view class="home-label">
                                        颜色
                                    </view>
                                </view>
                            </template>
                            <view class="home-right-style" @click="iconClick('color')">
                                <u-icon v-if="userData.colorShowText == null || userData.colorShowText == ''"
                                    name="plus-circle" color="#FF5184" size="26" />
                                <view class="status-text" v-else>
                                    {{
                    userData.colorShowText
                  }}
                                </view>
                            </view>
                        </uni-forms-item>
                        <uni-forms-item label="腰痛">
                            <template slot="label">
                                <view class="home-bottom-option">
                                    <u-icon name="https://miu-bloom.oss-cn-qingdao.aliyuncs.com/icon/from-icon-4.webp"
                                        size="30" />
                                    <view class="home-label">
                                        腰痛
                                    </view>
                                </view>
                            </template>
                            <view class="home-right-style" @click="iconClick('dysmenorrhea')">
                                <u-icon
                                    v-if="userData.dysmenorrheaShowText == null || userData.dysmenorrheaShowText == ''"
                                    name="plus-circle" color="#FF5184" size="26" />
                                <view class="status-text" v-else>
                                    {{
                    userData.dysmenorrheaShowText
                  }}
                                </view>
                            </view>
                        </uni-forms-item>
                    </view>
                    <uni-forms-item label="爱爱">
                        <template slot="label">
                            <view class="home-bottom-option">
                                <u-icon name="https://miu-bloom.oss-cn-qingdao.aliyuncs.com/icon/from-icon-5.webp"
                                    size="30" />
                                <view class="home-label">
                                    爱爱
                                </view>
                            </view>
                        </template>
                        <view class="home-right-style" @click="iconClick('havingSex')">
                            <u-icon v-if="userData.havingSexShowText == null || userData.havingSexShowText == ''"
                                name="plus-circle" color="#FF5184" size="26" />
                            <view class="status-text" v-else>
                                {{
                  userData.havingSexShowText
                }}
                            </view>
                        </view>
                    </uni-forms-item>
                    <uni-forms-item label="症状">
                        <template slot="label">
                            <view class="home-bottom-option">
                                <u-icon name="https://miu-bloom.oss-cn-qingdao.aliyuncs.com/icon/from-icon-6.webp"
                                    size="30" />
                                <view class="home-label">
                                    症状
                                </view>
                            </view>
                        </template>
                        <view class="home-right-style" @click="iconClick('zhengzhuang')">
                            <u-icon v-if="userData.symptomsShowText == null || userData.symptomsShowText == ''"
                                name="plus-circle" color="#FF5184" size="26" />
                            <view class="status-text" v-else>
                                {{
                  userData.symptomsShowText
                }}
                            </view>
                        </view>
                    </uni-forms-item>
                    <uni-forms-item label="白带">
                        <template slot="label">
                            <view class="home-bottom-option">
                                <u-icon name="https://miu-bloom.oss-cn-qingdao.aliyuncs.com/icon/from-icon-7.webp"
                                    size="30" />
                                <view class="home-label">
                                    白带
                                </view>
                            </view>
                        </template>
                        <view class="home-right-style" @click="iconClick('leucorrhea')">
                            <u-icon v-if="userData.leucorrheaShowText == null || userData.leucorrheaShowText == ''"
                                name="plus-circle" color="#FF5184" size="26" />
                            <view style="font-size: 30rpx;color: #FF5184;font-weight: bold" v-else>
                                {{
                  userData.leucorrheaShowText
                }}
                            </view>
                        </view>
                    </uni-forms-item>
                    <!-- <uni-forms-item label="心情">
            <template slot="label">
              <view class="home-bottom-option">
                <u-icon name="https://miu-bloom.oss-cn-qingdao.aliyuncs.com/icon/from-icon-10.webp" size="30"/>
                <view class="home-label">
                  心情
                </view>
              </view>
            </template>
            <view class="home-right-style">
              <u-icon name="plus-circle" color="#FF5184" size="26" @click="iconClick('xinqing')"/>
            </view>
          </uni-forms-item> -->
                </view>
            </uni-forms>
        </view>
        <!-- 流量弹出层组件 -->
        <flow-popup ref="heavyMenstrualPopup" @callback="popupCallback" />
        <!-- 颜色弹出层组件 -->
        <color-popup ref="colorPopup" @callback="popupCallback" />
        <!-- 痛经弹出层组件 -->
        <dysmenorrhea-popup ref="dysmenorrheaIndexPopup" @callback="popupCallback" />
        <!-- 爱爱弹出层组件 -->
        <having-sex-popup ref="havingSexPopup" @callback="popupCallback" />
        <!-- 症状弹出层组件 -->
        <symptoms-popup ref="symptomsPopup" @callback="popupCallback" />
        <!-- 白带弹出层组件 -->
        <leucorrhea-popup ref="leucorrheaPopup" @callback="popupCallback" />
    </view>
</template>

<script>
    import request from '@/api/request.js';
    import flowPopup from "@/pages/home/flowPopup.vue";
    import colorPopup from "@/pages/home/colorPopup.vue";
    import dysmenorrheaPopup from "@/pages/home/dysmenorrheaPopup.vue";
    import havingSexPopup from "@/pages/home/havingSexPopup.vue";
    import symptomsPopup from "@/pages/home/symptomsPopup.vue";
    import leucorrheaPopup from "@/pages/home/leucorrheaPopup.vue";
    import {
        conversionColor,
        conversionDysmenorrhea,
        conversionFlow,
        conversionHavingSex,
        conversionLeucorrhea,
        conversionSymptoms
    } from "@/api/commonArray";

    export default {
        components: {
            flowPopup,
            colorPopup,
            dysmenorrheaPopup,
            havingSexPopup,
            symptomsPopup,
            leucorrheaPopup
        },
        data() {
            return {
                barHeight: 0,
                statusBarHeight: 0,
                currentStatus: 1,
                userData: {
                    menstrualDayDetailVOList: [],
                    flow: "", // 流量
                    flowShowText: "",
                    color: "", // 颜色
                    colorShowText: "",
                    dysmenorrhea: "", // 痛经
                    dysmenorrheaShowText: "",
                    havingSex: "", // 爱爱
                    havingSexShowText: "",
                    physicalSymptoms: [], // 身体症状
                    vaginalDischarge: [], // 阴道分泌物
                    symptomsShowText: "",
                    leucorrhea: "", // 白带
                    leucorrheaShowText: "",
                    mood: 0 // 心情
                },
                today: new Date().toISOString().split('T')[0],
                isFutureFlag: false,
                menstrualText: ""
            }
        },
        methods: {
            // 大姨妈来了单选按钮组
            modelChange(index) {
                if (this.isFuture(this.today)) {
                    uni.showToast({
                        title: "不可以选择未来日期哦~",
                        icon: "none"
                    })
                    return
                }
                this.currentStatus = index
                // 发送数据
                uni.$u.throttle(() => request({
                    url: `/menstrual/newMenstrualPeriods`,
                    method: 'POST',
                    data: {
                        curDate: this.today,
                        flagStatus: this.currentStatus,
                        openid: uni.getStorageSync("miuUserInfo").openid
                    },
                    custom: {
                        showError: false,
                        showLoading: true,
                    }
                }).then((res) => {
                    // 触发日期切换
                    this.monthSwitch({
                        year: this.today.split('-')[0],
                        month: this.today.split('-')[1]
                    })
                }), 500, true)
            },
            // 日期变化触发
            selectDayChange(obj) {
                this.today = obj.fulldate
                this.month = obj.fulldate.split('-')[1]
                this.day = obj.fulldate.split('-')[2]
                // 判断是否是未来日期
                this.isFutureFlag = this.isFuture(this.today)
                // 判断今天是否在经期内
                this.isWithinMenstrualPeriod(obj.fulldate)
                // 查询当日数据状态
                this.getCurrentMenstrualInfo();
            },
            // 判断是否经期内
            isWithinMenstrualPeriod(currentFulldate) {
                for (var i = 0; i < this.userData.menstrualDayDetailVOList.length; i++) {
                    const temp = this.userData.menstrualDayDetailVOList[i]
                    if (temp.date == currentFulldate && temp.info == 1) {
                        this.currentStatus = 0
                        break;
                    } else {
                        this.currentStatus = 1
                    }
                }
            },
            // 判断是否是未来日期
            isFuture(str) {
                let d = new Date(str.replace(/-/g, '/'))
                let todaysDate = new Date()
                return d.setHours(0, 0, 0, 0) > todaysDate.setHours(0, 0, 0, 0)
            },
            // 初始化用户数据
            initUserInfo() {
                request({
                    url: `/wxUser/getInfo?openid=${uni.getStorageSync("miuUserInfo").openid}&today=${this.today}`,
                    method: 'GET',
                    custom: {
                        showError: false,
                        showLoading: true,
                    },
                }).then((res) => {
                    const userInfo = res.data || {}
                    uni.setStorageSync("miuUserInfo", userInfo)
                })
            },
            // 查询当日状态数据
            getCurrentMenstrualInfo() {
                uni.$u.throttle(() => request({
                    url: `/menstrual/selectMenstrualPeriods?openid=${uni.getStorageSync("miuUserInfo").openid}&curDate=${this.today}`,
                    method: 'GET',
                    custom: {
                        showError: false,
                        showLoading: true,
                    },
                }).then((res) => {
                    const userInfo = res.data || {}
                    this.userData.flow = userInfo.flow || ""
                    this.userData.color = userInfo.color || ""
                    this.userData.dysmenorrhea = userInfo.dysmenorrhea || ""
                    this.userData.havingSex = userInfo.havingSex || ""
                    this.userData.leucorrhea = userInfo.leucorrhea || ""
                    this.userData.physicalSymptoms = userInfo.physicalSymptoms || []
                    this.userData.vaginalDischarge = userInfo.vaginalDischarge || []
                    this.menstrualText = userInfo.menstrualText
                    // 转换
                    this.userData.flowShowText = conversionFlow(this.userData.flow);
                    this.userData.colorShowText = conversionColor(this.userData.color);
                    this.userData.dysmenorrheaShowText = conversionDysmenorrhea(this.userData.dysmenorrhea);
                    this.userData.havingSexShowText = conversionHavingSex(this.userData.havingSex);
                    this.userData.leucorrheaShowText = conversionLeucorrhea(this.userData.leucorrhea);
                    this.userData.symptomsShowText = conversionSymptoms(userInfo.physicalSymptoms || [],
                        userInfo.vaginalDischarge || []);
                }), 300, true)
            },
            // 月份切换
            monthSwitch(e) {
                request({
                    url: `/menstrual/checkMenstrualPeriodByMonth?openid=${uni.getStorageSync("miuUserInfo").openid}&curDate=${e.year + '-' + e.month + '-1'}`,
                    method: 'GET',
                    custom: {
                        showError: false,
                        showLoading: true,
                    }
                }).then((res) => {
                    this.userData.menstrualDayDetailVOList = res.data || []
                }).finally(() => {
                    // 判断今天是否经期内
                    this.isWithinMenstrualPeriod(this.today)
                })
            },
            iconClick(statusText) {
                if ("flow" == statusText) {
                    this.$nextTick(() => {
                        this.$refs.heavyMenstrualPopup.open(this.userData.flow);
                    })
                } else if ("color" == statusText) {
                    this.$nextTick(() => {
                        this.$refs.colorPopup.open(this.userData.color);
                    })
                } else if ("dysmenorrhea" == statusText) {
                    this.$nextTick(() => {
                        this.$refs.dysmenorrheaIndexPopup.open(this.userData.dysmenorrhea);
                    })
                } else if ("havingSex" == statusText) {
                    this.$nextTick(() => {
                        this.$refs.havingSexPopup.open(this.userData.havingSex);
                    })
                } else if ("zhengzhuang" == statusText) {
                    this.$nextTick(() => {
                        this.$refs.symptomsPopup.open(this.userData.physicalSymptoms, this.userData
                            .vaginalDischarge);
                    })
                } else if ("leucorrhea" == statusText) {
                    this.$nextTick(() => {
                        this.$refs.leucorrheaPopup.open(this.userData.leucorrhea);
                    })
                } else if ("xinqing" == statusText) {
                    console.log("点击了心情")
                }
            },
            popupCallback(callbackData) {
                switch (callbackData.from) {
                    case 'flow': {
                        this.userData.flow = callbackData.flowSelectData.value
                        this.userData.flowShowText = callbackData.flowSelectData.label
                        break;
                    }
                    case 'color': {
                        this.userData.color = callbackData.colorSelectData.value
                        this.userData.colorShowText = callbackData.colorSelectData.label
                        break;
                    }
                    case 'dysmenorrhea': {
                        this.userData.dysmenorrhea = callbackData.dysmenorrheaSelectData.value
                        this.userData.dysmenorrheaShowText = callbackData.dysmenorrheaSelectData.label
                        break;
                    }
                    case 'havingSex': {
                        this.userData.havingSex = callbackData.havingSexSelectData.value
                        this.userData.havingSexShowText = callbackData.havingSexSelectData.label
                        break;
                    }
                    case 'symptoms': {
                        // 症状
                        var finalShowText = []
                        this.userData.physicalSymptoms = []
                        this.userData.vaginalDischarge = []
                        for (let i = 0; i < callbackData.physicalSymptomsSelectData.length; i++) {
                            const temp = callbackData.physicalSymptomsSelectData[i]
                            this.userData.physicalSymptoms.push(temp.value)
                            finalShowText.push(temp.label)
                        }
                        for (let i = 0; i < callbackData.vaginalDischargeSelectData.length; i++) {
                            const temp = callbackData.vaginalDischargeSelectData[i]
                            this.userData.vaginalDischarge.push(temp.value)
                            finalShowText.push(temp.label)
                        }
                        if (finalShowText.length > 2) {
                            var tempLengthArr = [finalShowText[0], finalShowText[1]]
                            this.userData.symptomsShowText = tempLengthArr.join("、") + "共" + finalShowText.length + "种"
                        } else {
                            this.userData.symptomsShowText = finalShowText.join("、")
                        }
                        break;
                    }
                    case 'leucorrhea': {
                        this.userData.leucorrhea = callbackData.leucorrheaSelectData.value
                        this.userData.leucorrheaShowText = callbackData.leucorrheaSelectData.label
                        break;
                    }
                }
                request({
                    url: `/menstrual/saveStateInformation`,
                    method: 'POST',
                    data: {
                        openid: uni.getStorageSync("miuUserInfo").openid,
                        curDate: this.today,
                        flow: this.userData.flow, // 流量
                        color: this.userData.color, // 颜色
                        dysmenorrhea: this.userData.dysmenorrhea, // 痛经
                        havingSex: this.userData.havingSex, // 爱爱
                        physicalSymptoms: this.userData.physicalSymptoms, // 身体症状
                        vaginalDischarge: this.userData.vaginalDischarge, // 阴道分泌物
                        leucorrhea: this.userData.leucorrhea // 白带
                    },
                    custom: {
                        showError: false,
                        showLoading: true,
                    }
                }).then((res) => {
                    // 查询数据
                    
                })
            }
        },
        onLoad() {
            // 状态栏高度
            this.statusBarHeight = uni.getSystemInfoSync().statusBarHeight;
            // 胶囊数据
            const {
                top,
                height
            } = wx.getMenuButtonBoundingClientRect();
            // 自定义导航栏高度 = 胶囊高度 + 胶囊的padding*2, 如果获取不到设置为36
            this.barHeight = height ? height + (top - this.statusBarHeight) : 36;
            // 加载用户数据
            this.initUserInfo()
            // 查询当日状态
            this.getCurrentMenstrualInfo()
            // 触发日期切换
            this.monthSwitch({
                year: this.today.split('-')[0],
                month: this.today.split('-')[1]
            })
        },
        // 下拉刷新
        onPullDownRefresh() {
            // 查询用户信息
            this.initUserInfo()
            // 查询当日状态
            this.getCurrentMenstrualInfo()
            // 触发日期切换
            this.monthSwitch({
                year: this.today.split('-')[0],
                month: this.today.split('-')[1]
            })
            setTimeout(() => {
                //结束下拉刷新
                uni.stopPullDownRefresh();
            }, 300);
        }
    }
</script>

<style lang="scss">
    @import "@/pages/home/index.less";
</style>